package com.github.tvbox.osc.ui.activity

import android.content.Context
import android.text.TextUtils
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import com.github.tvbox.osc.R
import com.github.tvbox.osc.base.BaseLazyFragment
import com.github.tvbox.osc.event.RefreshEvent
import com.github.tvbox.osc.event.ServerEvent
import com.github.tvbox.osc.ui.adapter.PinyinAdapter
import com.github.tvbox.osc.ui.adapter.SearchAdapter
import com.github.tvbox.osc.ui.dialog.RemoteDialog
import com.github.tvbox.osc.ui.tv.widget.SearchKeyboard
import com.github.tvbox.osc.util.FastClickCheckUtil
import com.github.tvbox.osc.viewmodel.SourceViewModel
import com.github.tvbox.osc.viewmodel.SourceViewModelKt
import com.orhanobut.logger.Logger
import com.owen.tvrecyclerview.widget.TvRecyclerView
import com.owen.tvrecyclerview.widget.V7LinearLayoutManager
import io.github.source.config.VodConfig
import io.github.source.media.bean.MediaBean
import io.github.source.media.bean.MediaResult
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * @ClassName: SearchFragment
 * @Description: (搜索)
 * @author: huangrongcai
 * @date: 2024/11/8
 *
 * @Copyright: 黄嵘才（HuangRc)
 */
class SearchFragment : BaseLazyFragment() {

    companion object {
        @JvmStatic
        fun newInstance(): SearchFragment {
            return SearchFragment()
        }

        @JvmStatic
        fun newInstance(word: String): SearchFragment {
            return SearchFragment()
        }
    }

    private lateinit var llLayout: View

    /**搜索输入框*/
    private lateinit var etSearch: EditText
    private lateinit var tvSearch: TextView
    private lateinit var tvClear: TextView
    private lateinit var tvAddress: TextView
    private lateinit var ivQRCode: ImageView

    /**输入键盘*/
    private lateinit var keyboard: SearchKeyboard

    /**搜索结果*/
    private lateinit var mSearchGridView: TvRecyclerView

    /**搜索热词*/
    private lateinit var mHotWordGridView: TvRecyclerView
    var searchTitle: CharSequence? = ""
    var searchAdapter: SearchAdapter? = null
    var wordAdapter: PinyinAdapter? = null
    private lateinit var sourceViewModel: SourceViewModelKt

    override fun getLayoutResID(): Int {
        return R.layout.fragment_search
    }

    override fun init() {
        super.init()
        initViewModel()
    }

    override fun initView() {
        super.initView()

        llLayout = findViewById(R.id.skin_search_LlLayout)
        etSearch = findViewById(R.id.skin_search_EtSearch)
        tvSearch = findViewById(R.id.skin_search_TvSearch)
        tvClear = findViewById(R.id.skin_search_TvClear)
        tvAddress = findViewById(R.id.skin_search_TvAddress)
        ivQRCode = findViewById(R.id.skin_search_IvQRCode)
        keyboard = findViewById(R.id.skin_search_KeyBoardRoot)
        mSearchGridView = findViewById(R.id.skin_search_MGridView)
        mHotWordGridView = findViewById(R.id.skin_search_MGridViewWord)


        //Grid 热词
        mHotWordGridView?.setHasFixedSize(true)
        mHotWordGridView?.setLayoutManager(V7LinearLayoutManager(this.mContext, 1, false))
        wordAdapter = PinyinAdapter()
        mHotWordGridView?.setAdapter(wordAdapter)

        wordAdapter?.setOnItemClickListener { adapter, view, position ->
            search(wordAdapter?.getItem(position))
        }

        //Grid 搜索结果
        mSearchGridView?.setHasFixedSize(true)
        //UI
        mSearchGridView?.setLayoutManager(V7LinearLayoutManager(this.mContext, 1, false))
        searchAdapter = SearchAdapter()
        mSearchGridView?.setAdapter(searchAdapter)

        searchAdapter?.setOnItemClickListener { adapter, view, position ->
            FastClickCheckUtil.check(view)
            val video = searchAdapter?.data?.get(position)
            if (video != null) {
                try {
                    DetailActivityKt.start(video)
                } catch (th: Throwable) {
                    th.printStackTrace()
                }

            }
        }

        //#点击搜索按钮
        tvSearch.setOnClickListener { view ->
            FastClickCheckUtil.check(view)
            val wd = etSearch?.getText().toString().trim()
            if (!TextUtils.isEmpty(wd)) {
                search(wd)
            } else {
                Toast.makeText(mContext, "输入内容不能为空", Toast.LENGTH_SHORT).show()
            }
        }
        //#清除搜索框
        tvClear.setOnClickListener {
            FastClickCheckUtil.check(view)
            etSearch?.setText("")
        }

        //键盘事件
        keyboard?.setOnSearchKeyListener { pos, key ->
            if (pos > 1) {
                //输入
                var text = etSearch?.getText().toString().trim()
                text = text + key
                etSearch?.setText(text)
                if (text.isNotEmpty()) {
                    loadRec(text)
                }
            } else if (pos == 1) {
                var text = etSearch?.getText().toString().trim()
                if (text.isNotEmpty()) {
                    text = text.substring(0, text.length - 1)
                    etSearch?.setText(text)
                }
                if (text.isNotEmpty()) {
                    loadRec(text)
                }
            } else if (pos == 0) {
                val remoteDialog = RemoteDialog(mContext)
                remoteDialog.show()
            }

        }

    }

    fun initViewModel() {
        sourceViewModel = ViewModelProvider(this)[SourceViewModelKt::class.java]
        // 观察 categoryResult LiveData，当数据变化时更新 UI
        sourceViewModel.searchResult.observe(this) { result ->
            showSuccess()
            // 检查结果是否为空
            result?.let {
                // 初始化分类标签和ViewPager的数据
                onHandleSearchData(it)
            } ?: run {
                // 如果结果为空，初始化为空数据
                //输出日志
            }
        }
        //获取联想
        sourceViewModel.queryWord.observe(this) { result ->
            showSuccess()
            // 检查结果是否为空
            result?.let {
                // 初始化分类标签和ViewPager的数据
                queryHotWords(it)
            } ?: run {
                // 如果结果为空，初始化为空数据
                //输出日志
            }
        }

    }

    override fun initData() {
        super.initData()
        //刷新二维码
        refreshQRCode();
        // 初始化数据
        val intent = activity?.intent
        if (intent != null && intent.hasExtra("title")) {
            val title = intent.getStringExtra("title")
            showLoading()
            search(title)
        }
        //加载热词
        loadRec("")
    }

    //#搜索
    fun search(title: String?) {
        cancel()
        showLoading()
        this.searchTitle = title
        mSearchGridView?.visibility = View.INVISIBLE
        searchAdapter?.setNewData(null)
        searchResult()
    }

    fun loadRec(title: String?) {
        sourceViewModel.fetchRecWords(title.toString())
    }

    fun cancel() {
        //取消搜索
    }

    fun searchResult() {
        try {
            val sites = VodConfig.get().sites.filter { it.isSearchable }
            if (sites.isEmpty()) {
                Logger.i("No searchable sites found.")
                searchAdapter?.setNewData(null)
                return
            }

            sites.forEach { site ->
                try {
                    sourceViewModel.fetchSearch(site.key, searchTitle.toString())
                } catch (e: Exception) {
                    Logger.e("Search failed for ${site.key}", e)
                }
            }

        } catch (th: Throwable) {
            th.printStackTrace()
        } finally {
            searchAdapter?.setNewData(null)
        }

    }

    //搜索结果
    private fun onHandleSearchData(result: MediaResult<List<MediaBean>>) {
        val dataList = result.data?.filter {
            // 避免空指针 + 忽略大小写匹配
            it.getVodName().contains(searchTitle.toString(), ignoreCase = true)
        }
        if (dataList == null) {
            showNoResult()
            return
        }
        if (searchAdapter?.data?.isNotEmpty() == true) {
            searchAdapter?.addData(dataList)
        } else {
            showSuccess()
            mSearchGridView?.visibility = View.VISIBLE
            searchAdapter?.setNewData(dataList)
        }

    }

    private fun showNoResult() {
        // 显示“无结果”占位图
        // 可以展示空视图：emptyView?.visibility = View.VISIBLE
    }

    private fun showError(message: String? = null) {
        // 显示错误提示，如 Toast 或 SnackBar
        // 可记录日志：Logger.e(TAG, "Search error: $message")
    }

    private fun queryHotWords(list: List<String>) {
        wordAdapter?.setNewData(list)
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        EventBus.getDefault().register(this);
    }

    override fun onDetach() {
        super.onDetach()
        cancel()
        EventBus.getDefault().unregister(this);
    }

    //    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void server(ServerEvent event) {
//        if (event.type == ServerEvent.SERVER_SEARCH) {
//            String title = (String) event.obj;
//            showLoading();
//            search(title);
//        }
//    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun server(event: ServerEvent) {
        try {
            if (event.type == RefreshEvent.TYPE_SEARCH_RESULT) {
                val title = event.obj as String
                showLoading();
                search(title);
            }
        } catch (e: Exception) {
            onHandleSearchData(MediaResult.empty());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun refresh(event: RefreshEvent) {
        if (event.type == RefreshEvent.TYPE_SEARCH_RESULT) {
            try {
            } catch (e: Exception) {
                onHandleSearchData(MediaResult.empty());
            }
        }
    }

    private fun refreshQRCode() {
//        val address = ControlManager.get().getAddress(false);
//        tvAddress?.setText(
//            String.format(
//                "远程搜索使用手机/电脑扫描下面二维码或者直接浏览器访问地址\n%s",
//                address
//            )
//        );
//        ivQRCode?.setImageBitmap(QRCodeGen.generateBitmap(address, 300, 300));
    }
}